const { classModel, stuModel, classStudent } = require('../../model');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

module.exports = {
  list: async (req, res) => {
    const { page, limit } = req.query;
    let LIMIT = null, OFFSET = null;

    if (limit && page) {
      LIMIT = parseInt(limit);
      OFFSET = (parseInt(page) - 1) * LIMIT;
    }
    const result = await classModel.findByFilterLimit([
        'id', 'name', 'type', 'teacher', 'startAt'
      ], {
        org: req.decode.org
      }, LIMIT, OFFSET).catch(err => console.log(err));
    res.send({
      code: 20000,
      data: {
        total: result.length,
        items: result
      }
    })
  },
  create: async (req, res) => {
    const { name, type, teach, time } = req.body;

    await classModel.create({
      name: name,
      org: req.decode.org,
      type: type,
      teacher: teach,
      time: time,
      updatedAt: Date.now(),
      createdAt: Date.now()
    }).catch(err => { console.log('errMessage: ' + err)});
    res.send({
      code: 20000,
      message: '班级创建成功'
    })
  },
  delete: async function(req,res) {
    const { id } = req.params;
    await classModel.delete({
      id: id,
      org: req.decode.org
    }).catch(err => { console.log(err) });
    res.send({
      code: 20000,
      message: '班级删除成功'
    });
  },
  addStudent: function (req,res) {
    const { list } = req.body;
    const { id } = req.params;
    if (!id) {
      return res.send({
        code: 10000
      });
    }
    const classID = parseInt(id);
    if(classID === -1) {
      classStudent.delete({
        stu_id: {
          [Op.or]: list
        }
      }).then(() => {
        return res.send({
          code: 20000,
          message: '修改成功'
        });
      }).catch(err => {
        console.log(err);
        return res.send({
          code: 10000,
          message: '修改失败'
        });
      })
    } else {
      classStudent.findByFilter(['stu_id'],{
        stu_id: {
          [Op.or]: list
        },
        class_id: classID
      }).then(result => {
        let List = [];
        let temp = [];
        if (result.length !== 0){
          for (const item of result) {
            temp[item.stu_id] = true;
          }
        }
        for (const student of list) {
          if (!temp[student]){
            const config = {
              stu_id: student,
              class_id: classID
            };
            List.push(config)
          }
        }
        classStudent.createBatch(List).then(() => {
          return res.send({
            code: 20000,
            message: '添加成功'
          });
        }).catch(err => {
          console.log(err);
          return res.send({
            code: 10000,
            message: '添加失败'
          });
        })
      })
    }

  }
};
